<template>
  <el-dialog v-model="show" title="菜单权限分配">
    <template #default>
      <el-tree
        ref="myTree"
        :data="asyncRoutes"
        :props="defaultProps"
        show-checkbox
        node-key="name"
      ></el-tree>
    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { asyncRoutes } from '@/router'
import { updateUserPermission } from '@/api/user'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['ok'])

let curId = '' // 当前编辑的用户的Id
const show = ref(false)
const myTree = ref()

const defaultProps = {
  label: (data: any) => {
    return data.meta.title
  }
}

// 提交
async function handleConfirm() {
  // 1. 要获取到 el-tree 勾选了哪些节点的key, 返回的数据是一个数组 ['dashboard_console']
  //    这份数据正好可以用于给用户分配权限
  const checkedKeys = myTree.value.getCheckedKeys()

  // 2. 调用接口，修改用户信息
  await updateUserPermission(curId, checkedKeys)

  // 3. 修改成功
  ElMessage.success('修改成功')

  // 4. 关闭弹窗
  show.value = false

  // 5. 通知父组件更新
  emit('ok')
  // console.log('checkedKeys', checkedKeys)
}

defineExpose({
  open(user: any) {
    // 打开弹窗
    show.value = true

    // 设置Id
    curId = user.id

    nextTick(() => {
      // 将用户现在的权限回填到 el-tree 上，使用的是 el-tree 组件实例的 setCheckedKeys()
      myTree.value.setCheckedKeys(user.permissions)
    })
  },

  close() {
    show.value = false
  }
})
</script>
